package com.kzj.xfxh.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kzj.common.constant.GlobalConstant;
import com.kzj.common.exception.XfxhApiException;
import com.kzj.xfxh.entity.JsonParse;
import com.kzj.xfxh.entity.RoleContent;
import com.kzj.xfxh.entity.Text;
import com.kzj.xfxh.properties.XfxhProperties;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
//@Scope("prototype")
//@Component
public class XfxhApi extends WebSocketListener {
//    @Autowired
    XfxhProperties xfxhProperties;
    static Thread currThread=null;
    public static List<RoleContent> historyList=new ArrayList<>(); // 对话历史存储集合
    public static String question = "";
//    public static String answer=null;
    public static String totalAnswer=""; // 大模型的答案汇总
//    private static Boolean askFlag=true; // 控制提示用户是否输入
    public static final Gson gson = new Gson();
    private static Boolean wsCloseFlag=false;
    public void setXFXHProperties(XfxhProperties xfxhProperties)
    {
        this.xfxhProperties=xfxhProperties;
    }

    public void setXfxhProperties(XfxhProperties xfxhProperties)
    {
        this.xfxhProperties=xfxhProperties;
    }
    public  String ask(String content){
        if(currThread!=null)
            return GlobalConstant.WAIT_A_MOMENT;
        System.out.println(xfxhProperties);
        question=content;
            // 构建鉴权url
        String authUrl = null;
        try {
            authUrl = getAuthUrl(xfxhProperties.getHostUrl(), xfxhProperties.getApiKey(), xfxhProperties.getApiSecret());
        } catch (Exception e) {
            throw new XfxhApiException(e.getMessage());
        }
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();
        totalAnswer="";
        XfxhApi xfxhApi2 = new XfxhApi();
        xfxhApi2.setXfxhProperties(xfxhProperties);
        wsCloseFlag=false;
        client.newWebSocket(request,xfxhApi2);
        while(true)
        {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
//            System.out.println("currThread:"+currThread);
//            System.out.println("wsCloseFlag:"+wsCloseFlag);
            if(wsCloseFlag&&currThread==null)
                break;
        }
        return totalAnswer;
    }
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }

    class MyThread extends Thread {
        private WebSocket webSocket;

        public MyThread(WebSocket webSocket) {
            this.webSocket = webSocket;
        }

        public void run() {
            try {
                JSONObject requestJson=new JSONObject();

                JSONObject header=new JSONObject();  // header参数
                header.put("app_id",xfxhProperties.getAppId());
                header.put("uid","kzj");

                JSONObject parameter=new JSONObject(); // parameter参数
                JSONObject chat=new JSONObject();
                chat.put("domain",xfxhProperties.getDomain());
                chat.put("temperature",xfxhProperties.getTemperature());
                chat.put("max_tokens",xfxhProperties.getMaxTokens());
                parameter.put("chat",chat);

                JSONObject payload=new JSONObject(); // payload参数
                JSONObject message=new JSONObject();
                JSONArray text=new JSONArray();

                // 历史问题获取
                if(historyList.size()>0){
                    for(RoleContent tempRoleContent:historyList){
                        text.add(JSON.toJSON(tempRoleContent));
                    }
                }

                // 最新问题
                RoleContent roleContent=new RoleContent();
                roleContent.role="user";
                roleContent.content=question;
                text.add(JSON.toJSON(roleContent));
                historyList.add(roleContent);


                message.put("text",text);
                payload.put("message",message);


                requestJson.put("header",header);
                requestJson.put("parameter",parameter);
                requestJson.put("payload",payload);
                log.info(requestJson.toString()); // 可以打印看每次的传参明细
                webSocket.send(requestJson.toString());
                // 等待服务端返回完毕后关闭
                while (true) {
                    Thread.sleep(50);
                    if (wsCloseFlag) {
                        break;
                    }
                }
                webSocket.close(1000, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
            currThread=null;
        }
    }
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        MyThread myThread = new MyThread(webSocket);
        myThread.start();
        currThread=myThread;
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        System.out.println(text);
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
        if (myJsonParse.header.code != 0) {
            log.error("发生错误，错误码为：" + myJsonParse.header.code);
            log.error("本次请求的sid为：" + myJsonParse.header.sid);
            webSocket.close(1000, "");
        }
        List<Text> textList = myJsonParse.payload.choices.text;
        for (Text temp : textList) {
            totalAnswer=totalAnswer+temp.content;
        }
        if (myJsonParse.header.status == 2) {
            // 可以关闭连接，释放资源
            log.info("关闭连接\n**********************************************************************************************");
            if(canAddHistory()){
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswer);
                historyList.add(roleContent);
            }else{
                historyList.remove(0);
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswer);
                historyList.add(roleContent);
            }
            wsCloseFlag = true;
        }
        webSocket.close(1000, "");
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (null != response) {
                int code = response.code();
                log.error("onFailure code:" + code);
                log.error("onFailure body:" + response.body().string());
                if (101 != code) {
                    log.error("connection failed");
                    throw new XfxhApiException("connection failed");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static boolean canAddHistory(){  // 由于历史记录最大上线1.2W左右，需要判断是能能加入历史
        int history_length=0;
        for(RoleContent temp:historyList){
            history_length=history_length+temp.content.length();
        }
        if(history_length>12000){
            historyList.remove(0);
            historyList.remove(1);
            historyList.remove(2);
            historyList.remove(3);
            historyList.remove(4);
            return false;
        }else{
            return true;
        }
    }

}